//
//  ProjectListView.m
//  efairy
//
//  Created by 李锋 on 2019/1/2.
//  Copyright © 2019年 East. All rights reserved.
//

#import "ProjectListView.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "EFAModel.h"
#import "EFAPjtMgrResultsTVC.h"
#import "ProjectTableViewCell.h"
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "AreaAddressModel.h"
#import "YYModel.h"
#import "AddressCell.h"
#import "EFADeviceVC.h"
#import "DeviceList.h"
#import "EFAPjtMapVC.h"

@interface ProjectListView ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UITableView *addressTableView;
@property (nonatomic,strong) UIView *contentView;
@property (nonatomic,strong) UIView *addressChooseView;
@property (nonatomic,strong) UITextField *searchText;
@property (nonatomic,strong) UIView *checkAddress;
@property (nonatomic,strong) UILabel *addressLabel;
@property (nonatomic, strong) ProvinceListModel *addressModel;
@property (nonatomic, strong) NSMutableArray<EFAPjtListItem *> *projectList;
@property (nonatomic, assign) int pageIndex;
@property (nonatomic, strong) MJRefreshComponent *refreshViewComponent;
@property (nonatomic, strong) NSMutableArray<ProvinceModel *> *provinceArray;//省
@property (nonatomic, strong) NSMutableArray<CityModel *> *cityArray;//市
@property (nonatomic, strong) NSMutableArray<DistrictModel *> *districtArray;//县
@property (nonatomic, strong) NSMutableArray<TownshipModel *> *townshipArray;//区/街道
@property (nonatomic, strong) NSString *provinceId;//省id
@property (nonatomic, strong) NSString *cityId;//市
@property (nonatomic, strong) NSString *districtId;//县
@property (nonatomic, strong) NSString *townshipId;//区
@property (nonatomic, assign) int provinceArrayIndex;//选中省的第几个item
@property (nonatomic, assign) int cityArrayIndex;//选中市的第几个item
@property (nonatomic, assign) int districtArrayIndex;//选中区县的第几个item
@property (nonatomic, assign) int townshipArrayIndex;//选中街道的第几个item
@property (nonatomic, assign) int selectWhichAddress;//选择哪一个地址 0 省 1市 2 区县 3街道


//地址选择栏
@property (nonatomic,strong) UIView  *addressTopView;//地址选择页面的 透明部分view用于点击透明部分关闭view
@property (nonatomic,strong) UIView  *addressView;//地址选择部分的view
@property (nonatomic,strong) UILabel *confirm;//确认
@property (nonatomic,strong) UILabel *cancel;//取消
@property (nonatomic,strong) UILabel *provincen;//省title
@property (nonatomic,strong) UILabel *city;//市title
@property (nonatomic,strong) UILabel *district;//区县title
@property (nonatomic,strong) UILabel *township;//街道title
@property (nonatomic,strong) UIView *provincenLine;//省title 下划线
@property (nonatomic,strong) UIView *cityLine;//市title 下划线
@property (nonatomic,strong) UIView *districtLine;//区县title 下划线
@property (nonatomic,strong) UIView *townshipLine;//街道title 下划线
@property (nonatomic,strong) UIView *contentTableView;//tableview显示区域

@property (strong, nonatomic) UIBarButtonItem *mapBarBtnItem;






@end

@implementation ProjectListView

- (void)viewDidLoad {
     [super viewDidLoad];
//    [self setCellView];
    _projectList = [[NSMutableArray alloc]init];
    [self setView];
    [self initAddressViews];
    [self initNavigationBar];
    [self requestAddress];
   
}

//视图创建
- (void)viewWillAppear:(BOOL)animated{
   
//    [_cancel addTarget:self  action:@selector(onClickConfirm) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)initNavigationBar {
//    NSArray *titleArray = @[@"选择项目", @"选择项目", @"项目管理", @"选择项目"];
//    self.navigationItem.title = titleArray[self.viewType];
    self.navigationItem.title = @"选择项目";
//    self.navigationItem.rightBarButtonItem = self.serachBarBtnItem
     self.navigationItem.rightBarButtonItem = self.mapBarBtnItem;
    
}

#pragma mark - getters and setters
- (UIBarButtonItem *)mapBarBtnItem {
    if (!_mapBarBtnItem) {
        _mapBarBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"device_map"] style:UIBarButtonItemStylePlain target:self action:@selector(mapBarBtnTapped:)];
    }
    return _mapBarBtnItem;
}


#pragma mark - event response
- (void)mapBarBtnTapped:(UIBarButtonItem *)item {
    EFAPjtMapVC *vc = [[EFAPjtMapVC alloc] init];
    vc.pjtModel = [[EFAProjectModel alloc]init];
    vc.pjtModel.project_list = _projectList;
    [self showViewController:vc sender:nil];
}
-(void) setView{
    UIWindow *wd = [[UIApplication sharedApplication].windows lastObject];
    
    //actionbar高度
    float  navigationbar = self.navigationController.navigationBar.frame.size.height;
    NSLog(@"navigationbar height: %f", navigationbar);

    //背景view
    _contentView = [[UIView alloc]initWithFrame:CGRectMake(0, navigationbar+statusBarHeight, SCREEN_WIDTH, (SCREEN_HEIGHT-(navigationbar+statusBarHeight)))];
    _contentView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_contentView];
    
    //用于显示地址列表的view
    _addressChooseView = [[UIView alloc]initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,SCREEN_HEIGHT)];
//     _addressChooseView.backgroundColor = [UIColor blackColor];
//    _addressChooseView.alpha=0.5f;
     [wd addSubview:_addressChooseView];
    _addressChooseView.hidden=YES;
    
   
    
    
   //搜索栏背景
    UIView *searchBg =  [[UIView alloc]init];
    searchBg.layer.borderWidth=0.0f;
    searchBg.layer.cornerRadius=16.0f;
    searchBg.backgroundColor = ColorFromRGB(0xefefef);
    [_contentView addSubview:searchBg];
    
    //创建左侧搜索图标
    UIImageView *searchIcon=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 15, 15)];
    searchIcon.image=[UIImage imageNamed:@"search_icon"];
    [_contentView addSubview:searchIcon];
    
    //文本输入框
    _searchText = [[UITextField alloc]init];
    _searchText.backgroundColor = ColorFromRGB(0xefefef);
    _searchText.clearButtonMode=UITextFieldViewModeAlways;//只要输入框有内容就出现
    // 设置提示文字
    _searchText.placeholder = @"请输项目名称";
    _searchText.layer.borderWidth=0.0f;
    _searchText.layer.cornerRadius=16.0f;
    _searchText.returnKeyType = UIReturnKeySearch;//变为搜索按钮
    _searchText.delegate = self;//设置代理
    [_contentView addSubview:_searchText];
    
    //分割线
    UIView *horizontalLine = [[UIView alloc]init];
    horizontalLine.backgroundColor = ColorFromRGB(0xF2F2F2);
    [_contentView addSubview:horizontalLine];
    
    
    
    
    _checkAddress = [[UIView alloc]init];
    _checkAddress.width = SCREEN_WIDTH;
    _checkAddress.backgroundColor = [UIColor whiteColor];
  
    
    UITapGestureRecognizer *tapGesturRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickAddressView:)];
//    UITapGestureRecognizer * ges = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(click:)];
//    [ges addTarget:self action:@selector(haha)];
    [_checkAddress addGestureRecognizer:tapGesturRecognizer];
    
   
    
    _addressLabel = [[UILabel alloc]init];
    _addressLabel.text=@"选择地区";
    _addressLabel.textColor=ColorFromRGB(0x333333);
    _addressLabel.font= [UIFont systemFontOfSize:15.0];
    [_checkAddress addSubview:_addressLabel];
    
    //右箭头图标
    UIImageView *rightArrow=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 8, 13)];
    rightArrow.image=[UIImage imageNamed:@"icon_right_arrow"];
    [_checkAddress addSubview:rightArrow];
    
    _addressLabel.sd_layout
    .heightIs(15)
    .leftSpaceToView(_checkAddress, 16)
    .rightSpaceToView(_checkAddress, 16)
    .topSpaceToView(_checkAddress, 12.5);
    
    rightArrow.sd_layout.heightIs(13).widthIs(8)
    .topSpaceToView(_checkAddress, 13.5)
    .rightSpaceToView(_checkAddress, 16);
    
    [_contentView addSubview:_checkAddress];
    
    
    UIView *line2 = [[UIView alloc]init];
    line2.backgroundColor = BG;
    [_contentView addSubview:line2];
    
   
    
    self.tableView = [UITableView new];
    self.tableView.backgroundColor = BG;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //多余分割线不显示
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [_contentView sd_addSubviews:@[ self.tableView ]];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
     __weak typeof(self) weakSelf = self;
    //..下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.refreshViewComponent = weakSelf.tableView.mj_header;
            weakSelf.pageIndex = 1;
            [weakSelf requestPjtListWithHeader:YES];
    }];
    
   
    //..上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.refreshViewComponent = weakSelf.tableView.mj_footer;
        weakSelf.pageIndex = weakSelf.pageIndex + 1;
        [weakSelf requestPjtListWithHeader:NO];
    }];
    
    
   
    
    
    
     searchBg.sd_layout.heightIs(30)
    .topSpaceToView(_contentView, 7)
    .leftSpaceToView(_contentView, 16)
    .rightSpaceToView(_contentView, 16);
    
     searchIcon.sd_layout.heightIs(15)
    .widthIs(15)
    .topSpaceToView(_contentView, 15)
    .leftSpaceToView(_contentView, 32);
    
    _searchText.sd_layout.heightIs(30)
    .topSpaceToView(_contentView, 7)
    .leftSpaceToView(searchIcon, 12)
    .rightSpaceToView(_contentView, 16);
    
    horizontalLine.sd_layout.heightIs(1)
    .leftSpaceToView(_contentView, 0)
    .rightSpaceToView(_contentView, 0)
    .topSpaceToView(_searchText, 7);
    
    _checkAddress.sd_layout
    .heightIs(40)
    .topSpaceToView(horizontalLine, 0)
    .leftSpaceToView(_contentView, 0)
    .rightSpaceToView(_contentView, 0);
    
    line2.sd_layout
    .heightIs(10)
    .topSpaceToView(_checkAddress, 0)
    .leftSpaceToView(_contentView, 0)
    .rightSpaceToView(_contentView, 0);
    
    
//    UITabBarController *tabBarVC = [[UITabBarController alloc] init];//这儿取你当前tabBarVC的实例
//    CGFloat tabBarHeight = tabBarVC.tabBar.frame.size.height;
//    NSLog(@"tabbar%f高度",tabBarHeight);
   
    self.tableView.sd_layout
    .topSpaceToView(line2, 0)
    .leftSpaceToView(_contentView, 0)
    .rightSpaceToView(_contentView, 0)
    .bottomSpaceToView(_contentView, 0);
  
}



//搜索 这个函数是重写UITextFieldDelegate 当点击键盘搜索按钮触发
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    self.pageIndex = 1;
    [self requestPjtListWithHeader:YES];
    return YES;
}




#pragma mark - UITableViewDataSource
//返回行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
     if([tableView isEqual:self.tableView]){
         if (_projectList!=nil) {
             if (_projectList.count>0) {
                 return _projectList.count;
             }
         }
     }else if([tableView isEqual:self.addressTableView]){
         switch (_selectWhichAddress) {
             case 0:
                 if(_provinceArray != nil && _provinceArray.count > 0){
                     return _provinceArray.count;
                 }
                 break;
             case 1:
                 if(_cityArray != nil && _cityArray.count > 0){
                     return _cityArray.count;
                 }
                 break;
             case 2:
                 if(_districtArray != nil && _districtArray.count > 0){
                     return _districtArray.count;
                 }
                 break;
             case 3:
                 if(_townshipArray != nil && _townshipArray.count > 0){
                     return _townshipArray.count;
                 }
                 break;
             default:
                 break;
         }
         
     }
    return 0;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
  
    return NO;
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
}

//设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if([tableView isEqual:self.tableView]){
         ProjectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"ProjectListViewCell" description]];
        if(!cell){
            cell = [[ProjectTableViewCell alloc]init];
            cell.backgroundColor = [UIColor whiteColor];
        }
        [cell configViewWithPjtItem:_projectList[indexPath.row]];
        // 此步设置用于实现cell的frame缓存，可以让tableview滑动更加流畅
        [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
        return cell;
    }else{
        AddressCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"AddressCell" description]];
        if(!cell){
            cell = [[AddressCell alloc]init];
        }
        cell.backgroundColor = [UIColor whiteColor];
        switch (_selectWhichAddress) {
            case 0:
                [cell configViewWithItem:_provinceArray[indexPath.row]];
                if(_provinceArrayIndex == indexPath.row){
                    [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
                }
                break;
            case 1:
                 [cell configViewWithItem:_cityArray[indexPath.row]];
                if(_cityArrayIndex == indexPath.row){
                    [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
                }
                break;
            case 2:
                 [cell configViewWithItem:_districtArray[indexPath.row]];
                if(_districtArrayIndex == indexPath.row){
                    [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
                }
                break;
            case 3:
                 [cell configViewWithItem:_townshipArray[indexPath.row]];
                if(_townshipArrayIndex == indexPath.row){
                    [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
                }
                break;
            default:
                break;
        }
        // 此步设置用于实现cell的frame缓存，可以让tableview滑动更加流畅
        [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
        
        return cell;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [tableView cellHeightForIndexPath:indexPath cellContentViewWidth:SCREEN_WIDTH tableView:tableView];
//    return [tableView cellHeightForIndexPath: indexPath];
}


#pragma mark - UITableViewDelegate

//设置分割线
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}

//设置行高
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//    return 5.9;
//}

//点击cell执行该方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if([tableView isEqual:self.tableView]){
        if(_projectList.count > 0 && indexPath.row < _projectList.count){
//            EFADeviceVC *vc = [[EFADeviceVC alloc] init];
            DeviceList *vc = [[DeviceList alloc] init];
            vc.project_id = _projectList[indexPath.row].efairyproject_id;
            vc.project_name = _projectList[indexPath.row].efairyproject_name;
            [self showViewController:vc sender:nil];
        }
    }else if([tableView isEqual:self.addressTableView]){
        switch (_selectWhichAddress) {
            case 0:
                if(_provinceArrayIndex != (int)indexPath.row){//下标相同时表示已经为选中的数据，没不要在往下执行了
                    _provinceArrayIndex = (int)indexPath.row;//记录选择的下标，以便下次显示时知道是那条数据为选中的
                    if(_cityArrayIndex > -1){
                        _cityArrayIndex = -1;//重置为-1就是为了让其不是选中状态
                    }
                    if(_districtArrayIndex > -1){
                        _districtArrayIndex =-1;
                    }
                    if(_townshipArrayIndex > -1){
                        _townshipArrayIndex = -1;
                    }
                    _provincen.text = _provinceArray[indexPath.row].efairyprovince_name;
                    _city.text = @"请选择市";
                    _district.text = @"请选择区县";
                    _township.text = @"请选择街道";
                    _provinceId = _provinceArray[indexPath.row].efairyprovince_id;
                    _cityId = @"";
                    _districtId = @"";
                    _townshipId=@"";
                    _cityArray = _provinceArray[indexPath.row].city_list;
                    [_districtArray removeAllObjects];
                    [_townshipArray removeAllObjects];
                }
                break;
            case 1:
                if(_cityArrayIndex != (int)indexPath.row){
                    _cityArrayIndex= (int)indexPath.row;
                    if(_districtArrayIndex > -1){
                        _districtArrayIndex =-1;
                    }
                    if(_townshipArrayIndex > -1){
                        _townshipArrayIndex = -1;
                    }
                    _city.text = _cityArray[indexPath.row].efairycity_name;
                    _district.text = @"请选择区县";
                    _township.text = @"请选择街道";
                    _cityId =_cityArray[indexPath.row].efairycity_id;
                    _districtId = @"";
                    _townshipId=@"";
                    _districtArray = _cityArray[indexPath.row].district_list;
                    [_townshipArray removeAllObjects];
                }
                
                break;

            case 2:
                 if(_districtArrayIndex != (int)indexPath.row){
                     _districtArrayIndex = (int)indexPath.row;
                     if(_townshipArrayIndex > -1){
                         _townshipArrayIndex = -1;
                     }
                     _district.text = _districtArray[indexPath.row].efairydistrict_name;
                     _township.text = @"请选择街道";
                     _districtId = _districtArray[indexPath.row].efairydistrict_id;
                     _townshipId=@"";
                     _townshipArray = _districtArray[indexPath.row].township_list;
                 }
                
                break;
            case 3:
                if(_townshipArrayIndex !=(int)indexPath.row){
                    _township.text = _townshipArray[indexPath.row].efairytownship_name;
                    _townshipId =_townshipArray[indexPath.row].efairytownship_id;
                    _townshipArrayIndex = (int)indexPath.row;
                }
                break;
                
            default:
                break;
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}

//停止刷新头部或者底部
- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}




//刷新数据
- (void)refreshWholeView {
    [self.tableView reloadData];
}


//隐藏地址选择页面
-(void)isHiddenAddressView{
    if(_addressChooseView.isHidden){
        _addressChooseView.hidden=NO;
         [self.addressTableView reloadData];
    }else{
        _addressChooseView.hidden=YES;
    }
}

//点击地址选择入口栏
-(void)onClickAddressView:(id)tap{
    if(_provinceArray == nil  || _provinceArray.count == 0){
        [self requestAddress];
    }
    [self isHiddenAddressView];
}

//点击地址选择页面的透明部分
-(void)onClickAddressChooseView:(id)tap{
    [self isHiddenAddressView];
}


#pragma mark - network request
- (void)requestPjtListWithHeader:(BOOL)isHeader {
    // 发布Cos需要登录
    NSMutableDictionary *address  = [[NSMutableDictionary alloc]init];
    if(_provinceId != nil && _provinceId.length > 0){
        [address setObject:_provinceId forKey:@"efairyprovince_id"];
    }
    if(_cityId != nil && _cityId.length > 0){
        [address setObject:_cityId forKey:@"efairycity_id"];
    }
    if(_districtId != nil && _districtId.length > 0){
        [address setObject:_districtId forKey:@"efairydistrict_id"];
    }
    if(_townshipId != nil && _townshipId.length > 0){
        [address setObject:_townshipId forKey:@"efairytownship_id"];
    }
   
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:address
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&parseError];
    NSString * str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"区域json：%@",str);
    
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"regeo_info":str,
                           @"keyword": _searchText.text,
                           @"page":@(_pageIndex),
                           @"size":@"20"
                           };
     NSLog(@"项目列表参数：%@",pars);
    NSString *url = [ApiManager apiPjtList];
    [[XDAFNetworking sharedInstance] GET:url parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求项目列表返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        //把服务端返回的json格式数据解析为对象
        EFAProjectModel *proModel = [EFAProjectModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        //服务端返回本次请求的项目列表数据
        if(proModel.project_list != nil){
            if(isHeader){
                //下拉刷新
                _projectList = proModel.project_list;
            }else{
                //上啦加载追加数据到数组
                [_projectList addObjectsFromArray:proModel.project_list];
            }
            if(_projectList.count >= proModel.total_rows){
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                 [self.tableView.mj_footer resetNoMoreData];
            }
            
        }
        //刷新数据
        [self refreshWholeView];
       
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求项目列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}


-(void)requestAddress {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
       
        return;
    }
    NSDictionary *params =  @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                             @"access_token" : [EFAModel sharedInstance].loginInfo.access_token};
    NSString *url = [ApiManager apiPjtGeoInfoList];
    [[XDAFNetworking sharedInstance]GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task,id _Nullable responseObject){
//         NSLog(@"区域地址11：%@",responseObject[EFAGlobalJsonKeyResult]);
        
        ProvinceListModel *provinceModel=  [ProvinceListModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        _provinceArray =provinceModel.province_list;
        _provinceArrayIndex = 0;
        _cityArrayIndex = -1;
        _districtArrayIndex = -1;
        _townshipArrayIndex = -1;
        _selectWhichAddress = 0;
        if(_provinceArray.count > 0){
            //默认选择第一个省查询
            _addressLabel.text =_provinceArray[0].efairyprovince_name;//设置选择栏文字
            _provincen.text =_provinceArray[0].efairyprovince_name;//设置地址列表省份选择title文字
            _cityArray  = _provinceArray[0].city_list;//赋值默认查询省下面城市列表信息
            _provinceId =_provinceArray[0].efairyprovince_id;//默认省id
        }
        
        // 马上进入刷新状态
        [self.tableView.mj_header beginRefreshing];
        
    } failure:^(NSURLSessionDataTask *_Nullable task,NSError * _Nullable error){
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
    
}





-(void) onClickProvinceTitle:(id)tap{
    _selectWhichAddress = 0;
    _provincen.textColor =ColorFromRGB(0x282449);
    _city.textColor = ColorFromRGB(0x666666);
    _district.textColor = ColorFromRGB(0x666666);
    _township.textColor = ColorFromRGB(0x666666);
    _provincenLine.hidden=NO;
    _cityLine.hidden= YES;
    _districtLine.hidden=YES;
    _townshipLine.hidden=YES;
   [self.addressTableView reloadData];
    
}

-(void) onClickCityTitle:(id)tap{
    _selectWhichAddress = 1;
    _provincen.textColor =ColorFromRGB(0x666666);
    _city.textColor = ColorFromRGB(0x282449);
    _district.textColor = ColorFromRGB(0x666666);
    _township.textColor = ColorFromRGB(0x666666);
    _provincenLine.hidden=YES;
    _cityLine.hidden= NO;
    _districtLine.hidden=YES;
    _townshipLine.hidden=YES;
    [self.addressTableView reloadData];
    
}

-(void) onClickDistrictTitle:(id)tap{
    _selectWhichAddress = 2;
    _provincen.textColor =ColorFromRGB(0x666666);
    _city.textColor = ColorFromRGB(0x666666);
    _district.textColor = ColorFromRGB(0x282449);
    _township.textColor = ColorFromRGB(0x666666);
    _provincenLine.hidden=YES;
    _cityLine.hidden= YES;
    _districtLine.hidden=NO;
    _townshipLine.hidden=YES;
    [self.addressTableView reloadData];
    
}

-(void) onClickTownshipTitle:(id)tap{
    _selectWhichAddress = 3;
    _provincen.textColor =ColorFromRGB(0x666666);
    _city.textColor = ColorFromRGB(0x666666);
    _district.textColor = ColorFromRGB(0x666666);
    _township.textColor = ColorFromRGB(0x282449);
    _provincenLine.hidden=YES;
    _cityLine.hidden= YES;
    _districtLine.hidden=YES;
    _townshipLine.hidden=NO;
    [self.addressTableView reloadData];
}

-(void) onClickConfirm:(id)tap{
     _addressChooseView.hidden=YES;
    self.pageIndex = 1;
    [self requestPjtListWithHeader:YES];
    NSString *adressStr =@"选择地区";
    if(_provinceId != nil && _provinceId.length > 0){
        adressStr = _provincen.text;
    }
    if(_cityId != nil && _cityId.length > 0){
        adressStr = [adressStr stringByAppendingString:_city.text];
    }
    if(_districtId != nil && _districtId.length > 0){
        adressStr = [adressStr stringByAppendingString:_district.text];
    }
    
    if(_townshipId != nil && _townshipId.length > 0){
        adressStr = [adressStr stringByAppendingString:_township.text];
    }
    _addressLabel.text = adressStr;
}

-(void) onClickCancel:(id)tap{
     _addressChooseView.hidden=YES;
}


-(void) initAddressViews{
    
    //    self.view.layoutMargins = UIEdgeInsetsMake(30, 0, 0, 0);
    
    _addressTopView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/2-96)];
    _addressTopView.backgroundColor = [UIColor blackColor];
    _addressTopView.alpha = 0.5;
    
    UITapGestureRecognizer *tapView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickAddressChooseView:)];
    [_addressTopView addGestureRecognizer:tapView];
    
    _addressView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT/2-96, SCREEN_WIDTH, SCREEN_HEIGHT-(SCREEN_HEIGHT/2-96))];
    _addressView.backgroundColor = [UIColor whiteColor];
    [_addressChooseView sd_addSubviews:@[_addressTopView,_addressView,]];
    
    _confirm = [[UILabel alloc]init];
    _confirm.text=@"确定";
    _confirm.font=[UIFont systemFontOfSize:15.0f];
    _confirm.userInteractionEnabled=YES;
    UITapGestureRecognizer *tapConfirm = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickConfirm:)];
    //    [_confirm targetForAction:@selector(onClickConfirm)tapConfirm withSender:tapConfirm];
    [_confirm addGestureRecognizer:tapConfirm];
    
    
    _cancel = [[UILabel alloc]init];
    _cancel.text=@"取消";
    _cancel.font=[UIFont systemFontOfSize:15.0f];
    _cancel.userInteractionEnabled=YES;
    UITapGestureRecognizer *tapCancel = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickCancel:)];
    [_cancel addGestureRecognizer:tapCancel];
    
    
    UIView *lineView = [[UIView alloc]init];
    lineView.backgroundColor = ColorFromRGB(0xefefef);
    
    _provincen = [[UILabel alloc]init];
    _provincen.text = @"请选择省";
    _provincen.font = [UIFont systemFontOfSize:12.0f];
    _provincen.textColor = ColorFromRGB(0x666666);
    _provincen.textAlignment= NSTextAlignmentCenter;
    _provincen.userInteractionEnabled =YES;
    UITapGestureRecognizer *tapProvincen = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickProvinceTitle:)];
    [_provincen addGestureRecognizer:tapProvincen];
    
    _provincenLine = [[UIView alloc]init];
    _provincenLine.height=2;
    _provincenLine.backgroundColor=ColorFromRGB(0x282449);
    
    _city = [[UILabel alloc]init];
    _city.text = @"请选择市";
    _city.font = [UIFont systemFontOfSize:12.0f];
    _city.textColor = ColorFromRGB(0x666666);
    _city.textAlignment= NSTextAlignmentCenter;
    _city.userInteractionEnabled=YES;
    UITapGestureRecognizer *tapCity = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickCityTitle:)];
    [_city addGestureRecognizer:tapCity];
    
    _cityLine = [[UIView alloc]init];
    _cityLine.height=2;
    _cityLine.backgroundColor=ColorFromRGB(0x282449);
    _cityLine.hidden =YES;
    
    _district = [[UILabel alloc]init];
    _district.text = @"请选择区县";
    _district.font = [UIFont systemFontOfSize:12.0f];
    _district.textColor = ColorFromRGB(0x666666);
    _district.textAlignment= NSTextAlignmentCenter;
    _district.userInteractionEnabled=YES;
    UITapGestureRecognizer *tapDistrict = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickDistrictTitle:)];
    [_district addGestureRecognizer:tapDistrict];
    
    _districtLine = [[UIView alloc]init];
    _districtLine.height=2;
    _districtLine.backgroundColor=ColorFromRGB(0x282449);
    _districtLine.hidden =YES;
    
    _township = [[UILabel alloc]init];
    _township.text = @"请选择街道";
    _township.font = [UIFont systemFontOfSize:12.0f];
    _township.textColor = ColorFromRGB(0x666666);
    _township.textAlignment= NSTextAlignmentCenter;
    _township.userInteractionEnabled=YES;
    UITapGestureRecognizer *tapTownship = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickTownshipTitle:)];
    [_township addGestureRecognizer:tapTownship];
    
    _townshipLine = [[UIView alloc]init];
    _townshipLine.height=2;
    _townshipLine.backgroundColor=ColorFromRGB(0x282449);
    _townshipLine.hidden =YES;
    
    UIView *lineView2 = [[UIView alloc]init];
    lineView2.backgroundColor = ColorFromRGB(0xefefef);
    
    _contentTableView = [[UIView alloc]init];
    _contentTableView.backgroundColor = [UIColor whiteColor];
    
//    self.tableView = [UITableView new];
//    self.tableView.backgroundColor = BG;
//    self.tableView.delegate = self;
//    self.tableView.dataSource = self;
//
//    //多余分割线不显示
//    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
//    self.automaticallyAdjustsScrollViewInsets = NO;
//    self.tableView.backgroundColor = [UIColor whiteColor];
//    [self.view sd_addSubviews:@[ self.tableView ]];
//
    
    [_addressView sd_addSubviews:@[_confirm,_cancel,lineView,_provincen,_provincenLine,_city,_cityLine,
                                _district,_districtLine,_township,_townshipLine,lineView2,_contentTableView]];
    _cancel.sd_layout
    .widthIs(50)
    .heightIs(15)
    .leftSpaceToView(_addressView, 24)
    .topSpaceToView(_addressView, 15);
    
    _confirm.sd_layout
    .widthIs(50)
    .heightIs(15)
    .topEqualToView(_cancel)
    .rightSpaceToView(_addressView, 0);
    
    lineView.sd_layout
    .heightIs(1)
    .topSpaceToView(_confirm, 15)
    .leftSpaceToView(_addressView, 0)
    .rightSpaceToView(_addressView, 0);
    
    _provincen.sd_layout
    .widthIs((SCREEN_WIDTH-24)/4)
    .heightIs(45)
    .leftSpaceToView(_addressView, 12)
    .topSpaceToView(lineView, 0);
    
    _city.sd_layout
    .widthIs((SCREEN_WIDTH-24)/4)
    .heightIs(45)
    .leftSpaceToView(_provincen, 0)
    .topSpaceToView(lineView, 0);
    
    _district.sd_layout
    .widthIs((SCREEN_WIDTH-24)/4)
    .heightIs(45)
    .leftSpaceToView(_city,0)
    .topSpaceToView(lineView, 0);
    
    _township.sd_layout
    .widthIs((SCREEN_WIDTH-24)/4)
    .heightIs(45)
    .leftSpaceToView(_district, 0)
    .topSpaceToView(lineView, 0);
    
    
    
    _provincenLine.sd_layout
    .widthIs((SCREEN_WIDTH-24)/4)
    .heightIs(2)
    .leftSpaceToView(_addressView, 12)
    .topSpaceToView(_provincen, 0);
    
    _cityLine.sd_layout
    .widthIs((SCREEN_WIDTH-24)/4)
    .heightIs(2)
    .leftSpaceToView(_provincenLine, 0)
    .topSpaceToView(_provincen, 0);
    
    _districtLine.sd_layout
    .widthIs((SCREEN_WIDTH-24)/4)
    .heightIs(2)
    .leftSpaceToView(_cityLine, 0)
    .topSpaceToView(_provincen, 0);
    
    _townshipLine.sd_layout
    .widthIs((SCREEN_WIDTH-24)/4)
    .heightIs(2)
    .leftSpaceToView(_districtLine, 0)
    .topSpaceToView(_provincen, 0);
    
    lineView2.sd_layout
    .topSpaceToView(_provincenLine, 0)
    .heightIs(1)
    .leftSpaceToView(_addressView, 0)
    .rightSpaceToView(_addressView, 0);
    
    _contentTableView.sd_layout
    .topSpaceToView(lineView2, 0)
    .bottomSpaceToView(_addressView, 0)
    .leftSpaceToView(_addressView, 0)
    .rightSpaceToView(_addressView, 0);
    
    
//    [_contentTableView addSubview:_addressTableView];
    self.addressTableView = [UITableView new];
    self.addressTableView.backgroundColor = [UIColor whiteColor];
    self.addressTableView.delegate = self;
    self.addressTableView.dataSource = self;
    [_contentTableView addSubview:self.addressTableView];
    
    
    self.addressTableView.sd_layout.topSpaceToView(_contentTableView, 0)
    .bottomSpaceToView(_contentTableView, 0)
    .leftSpaceToView(_contentTableView, 0)
    .rightSpaceToView(_contentTableView, 0);
    
    
    
}

@end
